package com.axxc.jpa.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.axxc.jpa.service.QQAuthService;

@RestController
@RequestMapping(value = "auth")
public class AuthController {
	private Logger logger = LoggerFactory.getLogger(AuthController.class);
	@Autowired
	private QQAuthService qqAuthService;

	// 访问登陆页面，然后会跳转到 QQ 的登陆页面
	@PostMapping(value = "qqLoginPage")
	public String qqLogin() throws Exception {
		String uri = qqAuthService.getAuthorizationUrl();
		return uri;
	}

	// qq授权后会回调此方法，并将code传过来
	@PostMapping(value = "getQQCode")
	public String getQQCode(String code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 根据code获取token
		String accessToken = qqAuthService.getAccessToken(code);
		// 保存 accessToken 到 cookie，过期时间为 30 天，便于以后使用
		Cookie cookie = new Cookie("accessToken", accessToken);
		cookie.setMaxAge(60 * 24 * 30);
		response.addCookie(cookie);

		// 本网站是将用户的唯一标识存在用户表中，大家也可以加一张表，存储用户和QQ的对应信息。
		// 根据openId判断用户是否已经绑定过
		String openId = qqAuthService.getOpenId(accessToken);
		return openId;
	}

}